// 全局变量
let refreshTimer = null;
let lastQueryCredentials = null;
let currentAbortController = null;
let userInitiatedAbort = false;

// DOM 元素
const accountForm = document.getElementById('accountForm');
const useDefaultCheckbox = document.getElementById('useDefault');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const loadingIndicator = document.getElementById('loading');
const errorAlert = document.getElementById('error-alert');
const errorMessage = document.getElementById('error-message');
const accountSection = document.getElementById('account-section');
const positionsSection = document.getElementById('positions-section');
const settingsSection = document.getElementById('settings-section');
const refreshBtn = document.getElementById('refreshBtn');
const settingsForm = document.getElementById('settingsForm');
const autoRefreshCheckbox = document.getElementById('autoRefresh');
const refreshIntervalInput = document.getElementById('refreshInterval');
const apiUrlInput = document.getElementById('apiUrl');
const noPositionsAlert = document.getElementById('no-positions');
const positionsTableBody = document.getElementById('positions-table-body');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 从本地存储加载设置
    loadSettings();
    
    // 从localStorage加载结果
    const savedResult = localStorage.getItem('accountResult');
    if (savedResult) {
        displayAccountInfo(JSON.parse(savedResult));
    }
    
    // 事件监听器
    accountForm.addEventListener('submit', handleFormSubmit);
    useDefaultCheckbox.addEventListener('change', toggleCredentialsInputs);
    refreshBtn.addEventListener('click', refreshData);
    settingsForm.addEventListener('submit', saveSettings);
    autoRefreshCheckbox.addEventListener('change', toggleAutoRefresh);
    
    // 导航链接点击事件
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const targetId = link.getAttribute('href').substring(1);
            if (targetId) {
                showSection(targetId);
                
                // 更新活动链接
                document.querySelectorAll('.nav-link').forEach(l => l.classList.remove('active'));
                link.classList.add('active');
            }
        });
    });
    
    // 初始化应用
    init();
});

// 处理表单提交
function handleFormSubmit(e) {
    e.preventDefault();
    
    // 获取凭据
    const useDefault = useDefaultCheckbox.checked;
    // 添加默认凭据调试日志
    console.log('使用默认凭据:', useDefault);
    const username = useDefault ? 'cps168' : usernameInput.value.trim();
    const password = useDefault ? 'alibaba' : passwordInput.value.trim();
    console.log('查询凭据 - 用户名:', username, '密码长度:', password ? '******' : '未提供');
    
    // 验证输入
    if (!useDefault && (!username || !password)) {
        showError('请输入用户名和密码，或选择使用默认凭据');
        return;
    }
    
    // 保存凭据用于刷新
    lastQueryCredentials = { username, password };
    
    // 查询账户信息
    queryAccount(username, password);
}

// 查询账户信息
async function queryAccount(username, password) {
    showLoading(true);
    hideError();
    
    // 取消之前的请求
    if (currentAbortController) {
        userInitiatedAbort = true;
        currentAbortController.abort();
    }
    
    try {
        const apiUrl = apiUrlInput.value.trim();
        
        if (!apiUrl) {
            throw new Error('请设置API地址');
        }
        
        // 创建新的AbortController
        const controller = new AbortController();
        currentAbortController = controller;
        let isTimeout = false;

        const timeoutId = setTimeout(() => {
            isTimeout = true;
            controller.abort();
        }, 30000); // 延长超时时间至30秒

        try {
            console.log('发起API请求:', apiUrl);
            console.log('请求参数:', { username, password: '******' });
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                },
                body: JSON.stringify({ username, password }),
                signal: controller.signal
            });
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP错误: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (!result.success) {
                throw new Error(result.message || '查询失败');
            }
            
            // 保存结果到localStorage
            localStorage.setItem('accountResult', JSON.stringify(result.data));
            displayAccountInfo(result.data);
            setupAutoRefresh();
            showLoading(false);
            
        } catch (error) {
            // 清除当前请求控制器
            currentAbortController = null;
            
            // 区分AbortError和其他错误
            if (error.name === 'AbortError') {
                if (isTimeout) {
                    showError(`请求超时，API地址: ${apiUrl}，请检查服务端是否运行或API地址是否正确`);
                } else if (!userInitiatedAbort) {
                    // 只有非用户主动取消的情况才显示提示
                    showError('查询已取消');
                } else {
                    // 用户主动取消，不显示错误
                    console.log('用户主动取消请求');
                }
            } else {
                showError(`查询失败: ${error.message}`);
            }
            hideAccountInfo();
        } finally {
            clearTimeout(timeoutId);
            userInitiatedAbort = false;
        }
    } catch (error) {
        showError(`处理请求时出错: ${error.message}`);
        hideAccountInfo();
        showLoading(false);
    }
}

// 显示账户信息
function displayAccountInfo(data, sectionId = 'home-section') {
    // 根据不同部分显示相应内容
    const showAccount = sectionId === 'home-section' || sectionId === 'account-section';
    const showPositions = sectionId === 'home-section' || sectionId === 'positions-section';

    // 显示账户资金信息
    if (showAccount) {
        const account = data.account;
        document.getElementById('available').textContent = formatCurrency(account.available);
        document.getElementById('balance').textContent = formatCurrency(account.balance);
        document.getElementById('margin').textContent = formatCurrency(account.margin);
        document.getElementById('risk-ratio').textContent = formatPercentage(account.risk_ratio);
        document.getElementById('pre-balance').textContent = formatCurrency(account.pre_balance);

        // 设置浮动盈亏颜色
        const floatProfitElement = document.getElementById('float-profit');
        if (floatProfitElement && account.float_profit !== undefined) {
            floatProfitElement.textContent = formatCurrency(account.float_profit);
            setValueColor(floatProfitElement, account.float_profit);
        }

        // 设置平仓盈亏颜色
        const closeProfitElement = document.getElementById('close-profit');
        if (closeProfitElement && account.close_profit !== undefined) {
            closeProfitElement.textContent = formatCurrency(account.close_profit);
            setValueColor(closeProfitElement, account.close_profit);
        }

        // 显示账户部分
        accountSection.classList.remove('d-none');
        accountSection.classList.add('fade-in');
    } else {
        // 隐藏账户部分
        accountSection.classList.add('d-none');
    }

    // 显示持仓信息
    if (showPositions) {
        displayPositions(data.positions);
        // 显示持仓部分
        positionsSection.classList.remove('d-none');
        positionsSection.classList.add('fade-in');
    } else {
        // 隐藏持仓部分
        positionsSection.classList.add('d-none');
    }
}

// 显示持仓信息
function displayPositions(positions) {
    // 清空表格
    positionsTableBody.innerHTML = '';
    
    if (positions && positions.length > 0) {
        // 隐藏无持仓提示
        noPositionsAlert.classList.add('d-none');
        
        // 添加持仓数据
        positions.forEach(position => {
            const row = document.createElement('tr');
            
            // 合约
            const symbolCell = document.createElement('td');
            symbolCell.textContent = position.symbol;
            symbolCell.classList.add('fw-bold');
            row.appendChild(symbolCell);
            
            // 多头持仓
            row.appendChild(createCell(position.pos_long));
            
            // 空头持仓
            row.appendChild(createCell(position.pos_short));
            
            // 今日多开
            row.appendChild(createCell(position.volume_long_today));
            
            // 今日空开
            row.appendChild(createCell(position.volume_short_today));
            
            // 多头盈亏
            const longProfitCell = createCell(formatCurrency(position.float_profit_long));
            setValueColor(longProfitCell, position.float_profit_long);
            row.appendChild(longProfitCell);
            
            // 空头盈亏
            const shortProfitCell = createCell(formatCurrency(position.float_profit_short));
            setValueColor(shortProfitCell, position.float_profit_short);
            row.appendChild(shortProfitCell);
            
            // 多头均价
            row.appendChild(createCell(formatCurrency(position.position_price_long)));
            
            // 空头均价
            row.appendChild(createCell(formatCurrency(position.position_price_short)));
            
            positionsTableBody.appendChild(row);
        });
    } else {
        // 显示无持仓提示
        noPositionsAlert.classList.remove('d-none');
    }
}

// 创建表格单元格
function createCell(content) {
    const cell = document.createElement('td');
    cell.textContent = content;
    return cell;
}

// 设置值的颜色（正值为绿色，负值为红色）
function setValueColor(element, value) {
    if (value > 0) {
        element.classList.add('positive');
        element.classList.remove('negative');
    } else if (value < 0) {
        element.classList.add('negative');
        element.classList.remove('positive');
    } else {
        element.classList.remove('positive', 'negative');
    }
}

// 格式化货币
function formatCurrency(value) {
    if (value === null || value === undefined) return '0.00';
    return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(value);
}

// 格式化百分比
function formatPercentage(value) {
    if (value === null || value === undefined) return '0.00%';
    return new Intl.NumberFormat('zh-CN', {
        style: 'percent',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(value);
}

// 显示/隐藏加载指示器
function showLoading(show) {
    if (show) {
        loadingIndicator.classList.remove('d-none');
    } else {
        loadingIndicator.classList.add('d-none');
    }
}

// 显示错误信息
function showError(message) {
    errorMessage.textContent = message;
    errorAlert.classList.remove('d-none');
}

// 隐藏错误信息
function hideError() {
    errorAlert.classList.add('d-none');
}

// 隐藏账户信息
function hideAccountInfo() {
    accountSection.classList.add('d-none');
    positionsSection.classList.add('d-none');
}

// 切换凭据输入框
function toggleCredentialsInputs() {
    const disabled = useDefaultCheckbox.checked;
    usernameInput.disabled = disabled;
    passwordInput.disabled = disabled;
    
    if (disabled) {
        usernameInput.value = '';
        passwordInput.value = '';
    }
}

// 刷新数据
function refreshData() {
    if (lastQueryCredentials) {
        queryAccount(lastQueryCredentials.username, lastQueryCredentials.password);
    } else {
        showError('请先查询账户信息');
    }
}

// 设置自动刷新
function setupAutoRefresh() {
    // 清除现有定时器
    if (refreshTimer) {
        clearInterval(refreshTimer);
        refreshTimer = null;
    }
    
    // 如果启用了自动刷新
    if (autoRefreshCheckbox.checked) {
        const interval = parseInt(refreshIntervalInput.value) * 1000;
        // 设置最小间隔为3秒，防止过于频繁的请求
        const minInterval = 3000;
        const finalInterval = Math.max(interval, minInterval);
        refreshTimer = setInterval(refreshData, finalInterval);
    }
}

// 切换自动刷新
function toggleAutoRefresh() {
    setupAutoRefresh();
}

// 保存设置
function saveSettings(e) {
    e.preventDefault();
    
    // 获取设置值
    const apiUrl = apiUrlInput.value.trim();
    const refreshInterval = refreshIntervalInput.value.trim();
    const autoRefresh = autoRefreshCheckbox.checked;
    
    // 验证刷新间隔
    if (!/^\d+$/.test(refreshInterval) || parseInt(refreshInterval) < 30) {
        alert('刷新间隔必须是大于等于30的整数');
        return;
    }
    
    // 保存到本地存储
    localStorage.setItem('apiUrl', apiUrl);
    localStorage.setItem('refreshInterval', refreshInterval);
    localStorage.setItem('autoRefresh', autoRefresh);
    
    // 重新设置自动刷新
    setupAutoRefresh();
    
    // 显示成功消息
    alert('设置已保存');
    
    // 返回主页
    showSection('home-section');
}

// 加载设置
function loadSettings() {
    const apiUrl = localStorage.getItem('apiUrl');
    const refreshInterval = localStorage.getItem('refreshInterval');
    const autoRefresh = localStorage.getItem('autoRefresh');
    
    // 设置API地址
    if (apiUrl) apiUrlInput.value = apiUrl;
    else apiUrlInput.value = 'http://localhost:8000/get_account_info';
    
    // 设置刷新间隔（默认600秒）
    if (refreshInterval !== null) refreshIntervalInput.value = refreshInterval;
    else refreshIntervalInput.value = '600';
    
    // 设置自动刷新
    autoRefreshCheckbox.checked = autoRefresh === 'true';
}

// 显示指定部分
function showSection(sectionId) {
    // 隐藏所有部分
    document.querySelectorAll('.content-section').forEach(section => {
        section.classList.add('d-none');
        section.classList.remove('active', 'fade-in');
    });

    // 显示选定部分
    const section = document.getElementById(sectionId);
    if (section) {
        section.classList.remove('d-none');
        setTimeout(() => {
            section.classList.add('active', 'fade-in');
        }, 10);
    }

    // 特殊处理主页部分
    if (sectionId === 'home-section') {
        // 显示主页时加载保存的结果
        const savedResult = localStorage.getItem('accountResult');
        if (savedResult) {
            displayAccountInfo(JSON.parse(savedResult), 'home-section');
        }
        return;
    }

    // 仅在显示账户或持仓部分时加载数据
    if (sectionId === 'account-section' || sectionId === 'positions-section') {
        const savedResult = localStorage.getItem('accountResult');
        if (savedResult) {
            const result = JSON.parse(savedResult);
            displayAccountInfo(result.data, sectionId);
        } else {
            // 如果没有保存的结果，提示用户先查询
            showError('请先查询账户信息');
        }
    } else if (sectionId === 'settings-section') {
        // 显示设置部分时加载设置
        loadSettings();
    }
}

// 初始化应用
function init() {
    // 页面加载时显示主页
    showSection('home-section');
}